﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HealthUI : MonoBehaviour {

	public Monster bindMonster;
	RectTransform transformRect;
	public Image hpImage;
	private void Awake() {
		transformRect=transform.GetComponent<RectTransform>();	
		
		gameObject.SetActive(false);
	}
	public void BindHp(Monster monster){
		bindMonster=monster;
		monster.hpOnChange+=HpChange;
		monster.onDeath+=OnDeath;
		hpImage.fillAmount = 1;
		gameObject.SetActive(true);
	}

    private void OnDeath(Monster obj)
    {
        Clear();
    }

    private void HpChange(int newHp, int oldHp, int MaxHp)
    {
        hpImage.fillAmount=(float)newHp/MaxHp;
    }

    private void Update() {
		if(bindMonster==null){

			gameObject.SetActive(false);
			return;
		}
		transform.position=bindMonster.transform.position+Vector3.up*4;
		//Debug.Log("HP="+UIUtils.GetScreenPosByWorldPos(bindMonster.transform.position));
		//transformRect.anchoredPosition=UIUtils.GetScreenPosByWorldPos(bindMonster.transform.position);
	}
	public void Clear(){
		bindMonster.hpOnChange-=HpChange;
		bindMonster.onDeath-=OnDeath;
		bindMonster=null;
		hpImage.fillAmount=1;
		gameObject.SetActive(false);
	}
}

public class UIUtils{
	static RectTransform canvas;
	static Camera camera;
	public static Vector2 GetScreenPosByWorldPos(Vector3 pos){
		if(canvas==null){
			canvas=GameObject.Find("Canvas").GetComponent<RectTransform>();
		}
		if(camera==null){
			camera=Camera.main;
		}
		Vector3 temp=camera.WorldToViewportPoint(pos);
		Vector2 screenPos=Vector2.zero;
		screenPos.x=canvas.sizeDelta.x*temp.x;
		screenPos.y=canvas.sizeDelta.y*temp.y;
		return camera.WorldToScreenPoint(pos);
	}
}